package com.bxl.netty.simulator.client;

import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * <>
 *
 * @author baixl
 * @date 2020/11/21
 */
public class NioClient {

    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.socket().connect(new InetSocketAddress(8090));
            socketChannel.configureBlocking(false);
            //socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, Boolean.TRUE);
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            //不管获取到的是什么事件。channel都是可读可写的。但是 在获取的是 写事件时，进行读 可能读取不到数据。
            //注册写事件是一直可以写的，直到注册了读事件。
            while (true) {
                if (selector.select() > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isAcceptable()) {
                            //key.channel().register(selector, SelectionKey.OP_WRITE);
                        } else if (key.isWritable()) {
                            //只要有缓存空间就可以一直写
                            NioClient.write(key).register(selector,SelectionKey.OP_READ);
                            //key.cancel();
                                    //.register(selector, SelectionKey.OP_READ);
                        }else if(key.isReadable()){
                            SocketChannel channel = (SocketChannel) key.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            while(channel.read(byteBuffer) > 0){
                                byteBuffer.flip();
                                byte[] bytes = new byte[byteBuffer.remaining()];
                                byteBuffer.get(bytes);
                                System.out.println(new String(bytes));
                            }
                            NioClient.write(key);
                            //TimeUnit.SECONDS.sleep(10);
                            //读完了，注册写代表这次读操作结束，等待写操作
                            //channel.register(selector, SelectionKey.OP_WRITE);
                        }
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static SocketChannel write(SelectionKey key)throws Exception{
        /*String a = "client test=================================================================" +
                "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" +
                "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" + "===============================================================================" +
                "===================================================================" +
                "====================================================================================================finish";*/
        String  a ="client test ==finish";
        ByteBuffer byteBuffer = ByteBuffer.allocate(a.getBytes().length);
        ByteBuffer length = ByteBuffer.allocate(4);
        byte[] bytes = a.getBytes();
        length.putInt(bytes.length);
        byteBuffer.put(bytes);
        byteBuffer.flip();
        SocketChannel channel = (SocketChannel) key.channel();
        length.flip();
        channel.write(length);
        channel.write(byteBuffer);
        return channel;
        
    }
}
